import { reqUserInfo } from "@/api";
import { getToken, userInfo } from "@/utils/token";

const state = {
  code: "",
  token: getToken(),
  userInfo: {},
};

const mutations = {
  // 增加一个带参数的mutations方法，并且官方建议payload为一个对象.  调用的时候也需要传递一个对象
  GET_CODE(state, payload) {
    state.code = payload.code;
  },
  USER_TOKEN(state, payload) {
    state.token = payload.token;
  },
  USER_INFO(state, userInfo) {
    state.userInfo = userInfo;
  },
};

const actions = {
  getCode({ commit }, payload) {
    commit("GET_CODE", payload.code);
  },
  userToken({ commit }, payload) {
    console.log(payload)
    commit("USER_TOKEN", payload.token);
  },
  async userInfo({ commit }) {

    let result = await reqUserInfo();
    if (result.code == 200) {
      console.log(result.data)
      commit("USER_INFO", result.data);
      userInfo(result.data);
      return "ok";
    } else {
      return Promise.reject(new Error("faile")).catch((err) => {
        console.log(err);
      });
    }
  },
};

export default {
  state,
  mutations,
  actions,
};
